<template>
  <div class="thumbnail-list-content">
    <thumbnail
      v-if="isThumbnail"
      :data="data"
      @checkbox-change="checkboxChange"
      @operational-data-change="operationalDataChange"
      @edit-dialog="editDialog"
    ></thumbnail>
    <tableList
      v-else
      :data="data"
      @checkbox-change="checkboxChange"
      @operational-data-change="operationalDataChange"
      @edit-dialog="editDialog"
    ></tableList>
    <!-- 操作 -->
    <div class="operate" v-if="checkboxArr.length !== 0">
      <el-popover
        popper-class="custom-popover"
        placement="top-start"
        trigger="click"
        width="360"
        :teleported="false"
      >
        <template #reference>
          <el-button color="#0560FD" type="primary">移动至</el-button>
        </template>
        <!-- 移动至 tree -->
        <el-tree
          :data="categoryTreeData"
          :icon="getSvgIcon('ic_向右')"
          node-key="id"
          show-checkbox
          :check-strictly="true"
          :expand-on-click-node="false"
          :default-checked-keys="checkedKeys"
          :props="{
            children: 'children',
            label: 'categoryName',
          }"
          ref="treeRef"
          @node-click="handleNodeClick"
        />
      </el-popover>
      <template v-if="checkboxArr.length === 1">
        <el-button color="#0560FD" type="primary" @click="onPreview" v-if="!judgeDisable()" plain>
          预览
        </el-button>
        <el-button color="#0560FD" type="primary" @click="onEdit" v-if="isEdit" plain>
          编辑
        </el-button>
        <!-- <el-button color="#0560FD" type="primary" plain>升版</el-button> -->
        <el-button
          color="#0560FD"
          type="primary"
          @click="eventDownload"
          plain
          v-loading="isDownload"
        >
          导出
        </el-button>
      </template>
      <el-button color="#FF5454" type="danger" @click="eventDelete" plain>删除</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { thumbnailDataItem } from '../types';
import { useTree } from './../composables/tree';
import thumbnail from '../components/thumbnail.vue';
import tableList from '../components/table-list.vue';
import { getSvgIcon } from '@/components/svg-icon';
import { messageUtil } from '@jl/element-plus/utils';
import { deleteResource, downloadRsourceFile, dragResourceCategory } from '@/api/resource';
import { confirmAgain } from '@/utils';
import { useRouter } from 'vue-router';

defineOptions({
  name: 'ThumbnailList',
});

interface IProps {
  isThumbnail: boolean;
  data: thumbnailDataItem[];
}

interface Tree {
  id: string;
  label: string;
  children?: Tree[];
}

const props = withDefaults(defineProps<IProps>(), {
  isThumbnail: true,
  data: () => [],
});
const emit = defineEmits(['operationalDataChange', 'editDialog', 'checkChange']);
const checkboxArr = ref<thumbnailDataItem[]>([]);
const treeRef = ref<any>(null);
const checkedKeys = ref<any>([]);

const { categoryTreeData } = useTree();

/**
 *
 * 操作功能移动至功能相关
 */
// #region
const handleNodeClick = async (data: any) => {
  treeRef.value!.setCheckedKeys([], false);
  checkedKeys.value = [data.categoryId];
  if (data.categoryId === 'c1b21120-60f6-418e-a6d5-4146442d1b24') return;
  const CategoryIds = checkboxArr.value.map((item: any) => item.categoryId);
  const resourceIds = checkboxArr.value.map((item: any) => item.resourceId);
  const fData = new FormData();
  fData.set('CategoryIds', CategoryIds);
  fData.set('ResourceIds', resourceIds);
  fData.set('ToCategoryId', data.categoryId);
  fData.set('DragType', '0');
  dragResourceCategory({ data: fData }).then((res: any) => {
    if (res) {
      ElMessage({
        message: '移动成功',
        type: 'success',
      });
      props.data.forEach((item: any) => {
        item.checkbox = false;
      });
    } else {
      ElMessage({
        message: '移动失败',
        type: 'error',
      });
    }
    emit('operationalDataChange', true);
  });
};
const checkboxChange = (data: any) => {
  console.log(data, 'test-fbxtest-fbxtest-fbx');
  checkboxArr.value = data.filter((item: any) => item.checkbox);
  emit('checkChange', checkboxArr.value);
};

// #endregion
const operationalDataChange = (refresh?: boolean) => {
  emit('operationalDataChange', refresh);
};
const editDialog = (data: any) => {
  emit('editDialog', data);
};
// 预览
const router = useRouter();

const onPreview = () => {
  const currentObj: any = checkboxArr.value[0];
  if (
    !['gltf', '_3dtiles', 'tif_dem', 'tif_dom', 'shp', 'kml', 'json', 'jlg'].includes(
      currentObj.fileType
    )
  ) {
    return;
  }
  if (![63, 53].includes(currentObj.handleState)) {
    messageUtil.warning('资源正在处理中，无法加载');
    return;
  }
  router.push({
    path: `/resource/preview/${currentObj.resourceId}`,
  });
};

const judgeDisable = () => {
  const row: any = checkboxArr.value[0];
  if (['osgb'].includes(row.fileType) && row.configJson) {
    const configJson = JSON.parse(row.configJson);
    if (!configJson.IsChange) {
      return true;
    }
  }
  if (['tif_dom', 'tif_dem'].includes(row.fileType)) {
    if (!row.configJson) {
      return true;
    }
  }
  if (['terrain'].includes(row.fileType)) {
    return true;
  }
  if (row.handleState === 53 || row.handleState === 63) {
    return false;
  }
  return true;
};

// 删除
const eventDelete = async () => {
  const flag = await confirmAgain('确认删除该资源数据？', '删除操作不可逆，删除后将撤销展示。');
  if (!flag) return;
  const currentObj: any = checkboxArr.value[0];
  deleteResource({ params: { resId: currentObj.resourceId } }).then(() => {
    messageUtil.success('删除成功');
    emit('operationalDataChange', true, true);
  });
};

// 下载
const isDownload = ref(false);
const eventDownload = async () => {
  isDownload.value = true;
  const currentObj: any = checkboxArr.value[0];
  downloadRsourceFile({ params: { resourceId: currentObj.resourceId } })
    .then(() => {
      ElMessage({
        type: 'warning',
        message: `正在导出资源包，请到【下载管理】里面查看`,
        customClass: 'warning-style',
      });
      isDownload.value = false;
    })
    .catch(() => {
      isDownload.value = false;
    });
};

// const startDownLoad = (downLink: string) => {
//   const link = document.createElement('a');
//   const linkUrl = `${process.env.VUE_APP_PROXY_BASE_URL}/${downLink}`;
//   link.href = linkUrl;
//   link.click();
// };

// 编辑
const onEdit = async () => {
  const currentObj: any = checkboxArr.value[0];
  emit('editDialog', { isReUpload: false, selRow: currentObj || null });
};

const isEdit = computed(() => {
  const currentObj: any = checkboxArr.value[0];
  return currentObj.handleState === 53 || currentObj.handleState === 63;
});
// 预览

/**
 * 生命周期
 */
onMounted(() => {
  console.log();
});
</script>

<style lang="less" scoped>
.thumbnail-list-content {
  display: flex;
  flex-direction: column;
  position: relative;
  flex: 1;
  overflow-y: hidden;
  .operate {
    height: 60px;
    padding-top: 15px;
    .el-button {
      width: 80px;
      height: 32px;
      margin-right: 16px;
      margin-left: 0;
    }
    .el-button--primary.is-plain,
    .el-button--danger.is-plain {
      background-color: transparent;
      border: 1px solid #0560fd;
      &:hover {
        color: #0560fd;
      }
      &:active,
      &:focus {
        border: 1px solid #0560fd;
        color: #0560fd;
        &:hover {
          color: #0560fd;
        }
      }
    }
    .el-button--danger.is-plain {
      background-color: transparent;
      border: 1px solid #ff5454;
      &:hover {
        color: #ff5454;
      }
    }
    // 移动至弹框

    // 去掉动画效果
    :deep(.el-collapse-transition-enter-active),
    :deep(.el-collapse-transition-leave-active) {
      transition: none;
    }
    :deep(.custom-popover) {
      border: none;
      padding: 10px 0;
      box-shadow: 0px 9px 28px 8px rgba(0, 0, 0, 0.05), 0px -4px 16px 0px rgba(0, 0, 0, 0.08),
        0px 3px 6px -4px rgba(0, 0, 0, 0.12);
      .el-tree {
        & > .el-tree-node {
          padding: 0 15px !important;
        }
        .el-tree-node {
          padding: 0;
          .el-tree-node__content {
            height: 38px;
            line-height: 38px;
            &:hover {
              background: #f5f7fa;
              color: #0560fd;
              .el-icon {
                color: #0560fd;
                &.is-leaf {
                  color: transparent;
                }
              }
            }
            .el-checkbox {
              display: none;
            }
          }
        }
      }
    }
  }
}
</style>
